package org.example;

public class Test5 {
    //leetcode 701 二叉搜索树中的插入操作 https://leetcode.cn/problems/insert-into-a-binary-search-tree/description/
    public TreeNode insertIntoBST(TreeNode root, int val) {
        TreeNode newNode = new TreeNode(val);
        if (root == null) return newNode;
        TreeNode cur = root, prev = null;
        while (cur != null) {
            prev = cur;
            if (val > cur.val) cur = cur.right;
            else if (val < cur.val) cur = cur.left;
            else return root;
        }
        if (val > prev.val) prev.right = newNode;
        else prev.left = newNode;
        return root;
    }
}
